<?php

namespace App\Services;

use App\Exceptions\BusinessException;
use App\Models\BaseModel;
use App\Models\Project;
use App\Models\ProjectCate;

class ProjectService extends BaseService
{
    /**
     * 项目列表
     * @param $page
     * @param $pageSize
     * @param $keyword
     * @return array
     */
    public function list($page, $pageSize, $keyword)
    {
        // 设置对象
        $model = Project::query();
        // 关键词
        if ($keyword) {
            $model = $model->where('project_name', 'like', '%' . $keyword . '%');
        }
        // 状态
        $model = $model->where('status', BaseModel::STATUS_ENABLE);
        // 获取列表
        $result = $model
            ->orderBy('sort', 'desc')
            ->orderBy('id', 'desc')
            ->paginate($pageSize, ['id', 'cate_id', 'project_name', 'project_img'], 'page', $page);

        $cateNames = ProjectCate::query()->pluck('cate_name', 'id')->toArray() ?? [];
        $result->getCollection()->transform(function ($item) use ($cateNames) {
            $item['cate_name'] = $cateNames[$item['cate_id']] ?? '';
            $item['project_img'] = storageFirst($item['project_img']);
            return $item;
        });

        return $this->successPage($result);
    }

    /**
     * 项目详情
     * @param $projectId
     * @return array
     * @throws BusinessException
     */
    public function detail($projectId)
    {
        // 获取数据
        $data = Project::query()->where('id', $projectId)->first();
        if (!$data) {
            $this->throwBusinessException('项目不存在');
        }
        $data->increment('views');
        $data = $data->toArray();

        $data['cate_name'] = ProjectCate::query()->where('id', $data['cate_id'])->value('cate_name');
        $data['project_img'] = storageMulti($data['project_img']);
        return $data;
    }
}
